package sushil.luc.navigation;

import java.util.ArrayList;

import org.w3c.dom.Document;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;

// found at : http://iamvijayakumar.blogspot.com/2013/04/android-draw-route-between-two-geo.html

public class GetRouteTask extends AsyncTask<String, Void, String> {
    
    private ProgressDialog Dialog;
    private String response = "";
    private Context parent;
    private GMapV2GetRouteDirection v2GetRouteDirection;
    private LatLng fromPosition;
    private LatLng toPosition;
    private  Document document;
    private GoogleMap map;
    private com.google.android.gms.maps.model.MarkerOptions markerOptions;
    
    public GetRouteTask(Context parent, LatLng fromPosition, LatLng toPosition, GoogleMap map)
    {
    	this.parent = parent;
    	v2GetRouteDirection = new GMapV2GetRouteDirection();
    	this.fromPosition = fromPosition;
    	this.toPosition = toPosition;
    	this.map = map;
    	this.markerOptions = new com.google.android.gms.maps.model.MarkerOptions();
    	
    }
    
    @Override
    protected void onPreExecute() {
          Dialog = new ProgressDialog(this.parent);
          Dialog.setMessage("Loading route...");
          Dialog.show();
    }

    @Override
    protected String doInBackground(String... urls) {
          //Get All Route values
                document = v2GetRouteDirection.getDocument(fromPosition, toPosition, GMapV2GetRouteDirection.MODE_DRIVING);
                Log.d("GetRoutTask", "doInBackground");
                response = "Success";
          return response;

    }

    @Override
    protected void onPostExecute(String result) {
          map.clear();
          if(response.equalsIgnoreCase("Success")){
        	  Log.d("GetRoutTask", "onPostExecute");
          ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
          PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.RED);

          for (int i = 0; i < directionPoint.size(); i++) {
                rectLine.add(directionPoint.get(i));
          }
          // Adding route on the map
          map.addPolyline(rectLine);
          markerOptions.position(toPosition);
          markerOptions.draggable(true);
          map.addMarker(markerOptions);

          }
         
          Dialog.dismiss();
    }
}
